Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

310
Vistas
How to send "token" to "Api" in "react"

I'm a new developer. If you login to our website, JWT will be created. When I press the button, I have to put it in the API as a backend. And if the screen is successful, the address in the API must be printed out. If it fails, 'authentication failure' should be displayed on the screen. I want to do this. Please help me.

import axios from 'axios';
import React, { useState } from 'react';
import { Button } from '@material-ui/core';

function TestPage() {
  const onLogin = () => {
    var variables = {
      email: email,
      password: password,
    };

    Axios.post('/auth/login', variables).then((res) => {
      setCookie('token', res.payload.accessToken);
      setCookie('exp', res.payload.accessTokenExpiresIn);
      Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
      Axios.get('/user/me').then((res) => {
        console.log(res);
      });
    });
  };

  return (
    <>
      <div>
        <Button
          variant="contained"
          color="primary"
          style={{ width: '200px' }}
          onClick={(e) => customFetch(e)}>
          address
        </Button>
      </div>
      {address && <div>{address}</div>}
    </>
  );
}

export default TestPage;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Generally for any network operation, it's helpful to know when it's in progress, has finished, and/or has an error. Let's set this up:

const [isLoading, setIsLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)

// inside your `onLogin` function...
setIsLoading(true);
Axios.post('/auth/login', variables).then((res) => {
  setCookie('token', res.payload.accessToken);
  setCookie('exp', res.payload.accessTokenExpiresIn);
  Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`;
  // bit messy using the same error state for both but you can always refactor
  Axios.get('/user/me').then((res) => {
        console.log(res);
        setData(res); // not sure where the actual data is with Axios
  }).catch(err => setError(err);
}).catch(err => setError(err));
setIsLoading(false);

During your POST, set the state variables accordingly:

  1. Before the post, setIsLoading(true)
  2. On success, setData(response.data) // whatever your payload might be
  3. On error/failure, setError(error)

Now in your component return, you can conditionally render your different states, e.g:

// your component body
if (isLoading) return (
  // a loading state
)
if (error) return (
  // an error state
  // e.g. "Authentication Failure"
)
return (
  // your success/ideal state
  // e.g:
  <>
    <div>
      <Button
        variant="contained"
        color="primary"
        style={{ width: '200px' }}
        onClick={(e) => customFetch(e)}>
        address
      </Button>
    </div>
    {address && <div>{address}</div>}
  </>
)

Alternatively, you could leverage the variables slightly differently:

return (
  <>
    <div>
      <Button
        variant="contained"
        color="primary"
        style={{ width: '200px' }}
        onClick={(e) => customFetch(e)}
        disabled={isLoading}>
        address
      </Button>
    </div>
    <div>
      {isLoading
        ? 'Checking...'
        : error !== null
        ? 'Something went wrong'
        : 'Ready to submit'}
    </div>
  </>
)

The ternary style can be a bit messy though.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda